
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:oral_cloud/config/app_config.dart';
import 'package:oral_cloud/config/constant.dart';
import 'package:oral_cloud/config/resource_mananger.dart';
import 'package:oral_cloud/config/router_manger.dart';
import 'package:oral_cloud/generated/l10n.dart';
import 'package:oral_cloud/provider/provider_widget.dart';
import 'package:oral_cloud/ui/widget/ButtonProgressIndicator.dart';
import 'package:oral_cloud/ui/widget/global_widget.dart';
import 'package:oral_cloud/ui/widget/text_field.dart';
import 'package:oral_cloud/view_model/login_model.dart';
import 'package:provider/provider.dart';

class LoginPage extends StatefulWidget {

  LoginPage();

  @override
  State<StatefulWidget> createState() {
    return _LoginPageState();
  }
}



class _LoginPageState extends State<LoginPage> {


  bool enableLogin=false;
  final _nameController = TextEditingController();
  final _pwdOrVCodeController = TextEditingController();
  final _pwdOrVCodeFocus = FocusNode();
  GlobalKey<_LoginButtonStatue> loginBtnKey = GlobalKey();
  GlobalKey<_PwdOrVCodeInputWidgetState> pwdOrVCodeInputKey = GlobalKey();
  GlobalKey<_ChangeLoginState> changeLoginKey = GlobalKey();
  @override
  void initState() {
    _nameController.addListener(_inputLister);
    _pwdOrVCodeController.addListener(_inputLister);
    super.initState();
  }

  _inputLister(){
    print(" _inputLister");
    bool enableLogin=_nameController.text.length>0&&_pwdOrVCodeController.text.length>0;
    print("enableLogin=$enableLogin");
    bool enableVCode=_nameController.text.length==11;
    print("enableVCode=$enableVCode");
    loginBtnKey?.currentState?.updateEnableLogin(enableLogin);
    pwdOrVCodeInputKey?.currentState?.widget?.vCodeInputKey?.currentState?.updateEnableVCode(enableVCode);
  }


  @override
  void dispose() {
    _nameController.removeListener(_inputLister);
    _pwdOrVCodeController.removeListener(_inputLister);
    _nameController.dispose();
    _pwdOrVCodeController.dispose();
    _pwdOrVCodeFocus.unfocus();
    _pwdOrVCodeFocus.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      resizeToAvoidBottomPadding: false, //输入框抵住键盘
      body: Column(
        children: [
          LoginLogo(),
          Container(
              margin: EdgeInsets.symmetric(vertical: ScreenUtil.getInstance().setHeight(AppConfig.loginInputMarginTop)),
              width: ScreenUtil.getInstance().setHeight(AppConfig.loginContainWidth),
              child: ProviderWidget2<LoginModel,VCodeModel>(
                model1: LoginModel(),
                model2: VCodeModel(),
                onModelReady: (model1,model2) =>
                    _nameController.text = model1.getLoginName(),
                builder: (context, model1,model2, child) {
                  return child;
                },
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    MyTextField(
                      prefixIcon:  Image.asset(
                        ImageHelper.wrapAssets('user.png'),
                        width: ScreenUtil.getInstance().setHeight(33),
                        height: ScreenUtil.getInstance().setHeight(33),
                      ),
                      prefixIconConstraints: BoxConstraints(
                        minWidth:ScreenUtil.getInstance().setHeight(100),
                        minHeight: ScreenUtil.getInstance().setHeight(50),
                      ),
                      contentPaddingV: ScreenUtil.getInstance().setHeight(AppConfig.contentPadding),
                      placeHolder: S.of(context).userName,
                      maxLength: 11,
                      keyboardType: TextInputType.phone,
                      controller: _nameController,
                      fontSize: FontSize.fontSizeXXL,
                    ),
                    SizedBox(height: ScreenUtil.getInstance().setHeight(AppConfig.inputVSpace)),
                    PwdOrVCodeInputWidget(pwdOrVCodeInputKey,_nameController,_pwdOrVCodeController,_pwdOrVCodeFocus),
                    SizedBox(height: ScreenUtil.getInstance().setHeight(AppConfig.loginTextMarginTop),),
                    Row(
                      children: [
                        ChangeLogin(changeLoginKey,S.of(context).vcodeLogin,leftClick: (){
                          pwdOrVCodeInputKey.currentState.changeLoginType();
                          changeLoginKey.currentState.changeLoginType(pwdOrVCodeInputKey.currentState.widget.loginType,context);
                        },),
                        Expanded(
                          child: ForgetPwd(S.of(context).forgetPassword,
                            rightClick: _jump2ModifyPassword,
                          ),
                        ),
                      ],
                    ),
                    SizedBox(height: ScreenUtil.getInstance().setHeight(AppConfig.btnMarginTop),),
                    LoginButton(loginBtnKey,_nameController, _pwdOrVCodeController,onPressed: (model) {
                      print('开始调用登录接口');
                      model
                          .login(_nameController.text, _pwdOrVCodeController.text,pwdOrVCodeInputKey.currentState.widget.loginType)
                          .then((value) {
                        if (value) {
                          print('跳转到主界面');
                          Navigator.pushReplacementNamed(context, RouteName.home);
                        } else {
                          model.showErrorMessage(context);
                        }
                      });
                    },),


                  ],
                ),
              ))
        ],
      ),
    );
  }

  _jump2ModifyPassword() {
    Navigator.of(context).pushNamed(RouteName.modify_password);
  }

}





// ignore: must_be_immutable
class PwdOrVCodeInputWidget extends StatefulWidget{
  final TextEditingController _nameController;
  final TextEditingController _pwdOrVCodeController;
  final FocusNode _pwdOrVCodeFocus;
  int loginType=LoginModel.LoginTypePwd;
  GlobalKey<VCodeInputWidgetStatue> vCodeInputKey = GlobalKey();
  PwdOrVCodeInputWidget(Key key,this._nameController, this._pwdOrVCodeController,this._pwdOrVCodeFocus,{this.loginType=LoginModel.LoginTypePwd}):super(key:key);
  @override
  State<StatefulWidget> createState() {
    return _PwdOrVCodeInputWidgetState();
  }

}

class _PwdOrVCodeInputWidgetState extends State<PwdOrVCodeInputWidget>{



  void changeLoginType(){
    print('--------changeLoginType--------');
    if(widget.loginType==LoginModel.LoginTypePwd){
      widget.loginType=LoginModel.LoginTypeVCode;
    }else{
      widget.loginType=LoginModel.LoginTypePwd;
    }
    setState(() {

    });
  }



  
  bool isLoginOfPassword(){
    return widget.loginType==LoginModel.LoginTypePwd;
  }
  @override
  Widget build(BuildContext context) {
    widget._pwdOrVCodeController.clear();
    Widget pwdOrVCodeWidget;
    if(isLoginOfPassword()){
      pwdOrVCodeWidget=MyTextField(
        focusNode: widget._pwdOrVCodeFocus,
        controller: widget._pwdOrVCodeController,
        placeHolder:S.of(context).password,
        isInputPwd:true,
        fontSize: FontSize.fontSizeXXL,
        prefixIcon:  Image.asset(
          ImageHelper.wrapAssets('password.png'),
          width: ScreenUtil.getInstance().setHeight(33),
          height: ScreenUtil.getInstance().setHeight(33),
        ),
        prefixIconConstraints: BoxConstraints(
          minWidth:ScreenUtil.getInstance().setHeight(100),
          minHeight: ScreenUtil.getInstance().setHeight(50),
        ),
        contentPaddingV: ScreenUtil.getInstance().setHeight(AppConfig.contentPadding),
      );
    }else {
      pwdOrVCodeWidget = VCodeInputWidget(widget.vCodeInputKey, widget._nameController, widget._pwdOrVCodeController,widget._pwdOrVCodeFocus);
    }
    return pwdOrVCodeWidget;
  }
  


}

// ignore: must_be_immutable
class ChangeLogin extends StatefulWidget {
  String title;
  final VoidCallback leftClick;

  ChangeLogin(Key key,this.title,{this.leftClick}):super(key:key);
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _ChangeLoginState();
  }

}

class _ChangeLoginState extends State<ChangeLogin>{

  changeLoginType(int loginType,BuildContext context){
    if(loginType==LoginModel.LoginTypePwd){
      this.widget.title=S.of(context).vcodeLogin;
    }else{
      this.widget.title=S.of(context).passwordLogin;
    }

    setState(() {

    });
  }
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new Container(
      alignment: Alignment.centerLeft,
      child: GestureDetector(
        child: NormalText(widget.title),
        onTap: widget.leftClick,
      ),
    );
  }

}





class ForgetPwd extends StatelessWidget {
  final String title;
  final VoidCallback rightClick;

  ForgetPwd(this.title,{this.rightClick});

  @override
  Widget build(BuildContext context) {
    return new Container(
      alignment: Alignment.centerRight,
      child: GestureDetector(
        child: NormalText(title),
        onTap: this.rightClick,
      ),
    );
  }
}

class LoginLogo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Container(
      width: double.infinity,
      margin: EdgeInsets.only(top: ScreenUtil.getInstance().setHeight(AppConfig.loginLogoMarginTop)),
      child: Image.asset(
        ImageHelper.wrapAssets('ic_launcher.png'),
        width: ScreenUtil.getInstance().setWidth(AppConfig.loginLogoSize),
        height: ScreenUtil.getInstance().setWidth(AppConfig.loginLogoSize),
      ),
    );
  }
}



// ignore: must_be_immutable
class VCodeInputWidget extends StatefulWidget{
  final TextEditingController _nameController;
  final TextEditingController _vCodeController;
  final FocusNode _vCodeFocus;

  bool enableVCode;
  VCodeInputWidget(Key key,this._nameController, this._vCodeController,this._vCodeFocus, {this.enableVCode:false}):super(key:key);
  @override
  State<StatefulWidget> createState() {
    return VCodeInputWidgetStatue();
  }

}



class VCodeInputWidgetStatue extends State<VCodeInputWidget> {
  GlobalKey<MyTextFieldState> myTextFieldKey = GlobalKey();

  @override
  void initState() {
    widget.enableVCode=widget._nameController.text.length==11;
    super.initState();
  }

  void updateEnableVCode(bool enableVCode) {
    if (widget.enableVCode == enableVCode) {
      print("------updateEnableVCode no need setState------");
      return;
    }
    setState(() {
      print("------updateEnableVCode setState------");
      widget.enableVCode = enableVCode;
    });
  }
  @override
  Widget build(BuildContext context) {
    var model = Provider.of<VCodeModel>(context);
    MyTextField textField=MyTextField(key:myTextFieldKey,
      fontSize: FontSize.fontSizeXXL,
      focusNode: widget._vCodeFocus,
      contentPaddingV: ScreenUtil.getInstance().setHeight(AppConfig.contentPadding),
      placeHolder: S.of(context).nodeVCode,
      controller: widget._vCodeController,
      maxLength: 4,
      enableClick: widget.enableVCode,
      keyboardType: TextInputType.phone,
      getVCode: () async{
        print('开始调用获取验证码接口');
        bool canGetVCode=await model.getVCode(widget._nameController.text)
            .then((value)  {
          if (value) {
            print('获取验证码接口成功,已发送到手机号:${widget._nameController.text}上!');
          } else {
            model.showErrorMessage(context);
          }
          return value;
        });
        print('canGetVCode=$canGetVCode');
        return canGetVCode;
      },
    );
    return textField;
  }
}





typedef LoginCallback = void Function(LoginModel model);

class LoginButton extends StatefulWidget{
  final LoginCallback onPressed;
  final TextEditingController nameController;
  final TextEditingController pwdOrVCodeController;
  LoginButton(Key key, this.nameController, this.pwdOrVCodeController, {this.onPressed}):super(key:key);
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _LoginButtonStatue();
  }

}

class _LoginButtonStatue extends State<LoginButton>{

  bool enableLogin=false;

  void updateEnableLogin(bool enableLogin){
    if(this.enableLogin==enableLogin){
      print("------updateEnableLogin no need setState------");
      return;
    }
    setState(() {
      print("------updateEnableLogin setState------");
      this.enableLogin=enableLogin;
    });
  }


    @override
  Widget build(BuildContext context) {
    // TODO: implement build
      var model = Provider.of<LoginModel>(context);
      return CommonButtonWidget(
        height: ScreenUtil.getInstance().setHeight(AppConfig.inputHeight),
        child: model.isBusy
            ? ButtonProgressIndicator()
            : Text(
          S.of(context).signIn,
          style:
          TextStyle(color: Colors.white, fontSize: FontSize.fontSizeL),
        ),
        onPressed: model.isBusy||!enableLogin
            ? null
            :(){
          widget.onPressed(model,);
        },
      );
  }
}



